package cn.jiangjiesheng.bootstrap.commons.utils;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.util.Map;


/**
 * Created by dev@jiangjiesheng.cn on 2019/12/10 16:55<br>
 * 如果不喜欢使用RestTemplate，也可以使用这个<br>
 */
@Slf4j
public class HttpUtils {

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final OkHttpClient client = new OkHttpClient();

    public static String post(String url, String json) {
        log.info("url={}", url);
        log.info("post data={}", json);

        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            @Cleanup Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception ex) {
            log.error("post-error:", ex);
        }

        return null;
    }

    public static String get(String url) {
        log.info("url={}", url);

        Request request = new Request.Builder().url(url).build();
        try {
            @Cleanup Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception ex) {
            log.error("get-error:", ex);
        }

        return null;
    }

    /**
     * get请求带cookie参数
     *
     * @param url
     * @param sessionId
     * @return
     */
    public static String get(String url, String sessionId) {
        log.info("url={},sessionId={}", url, sessionId);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("Cookie", "PHPSESSID=" + sessionId).url(url).build();
        try {
            @Cleanup Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception ex) {
            log.error("get-error:", ex);
        }
        return null;
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String post(String url, Map<String, String> params, String sessionId) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request
                .Builder()
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                .addHeader("Cookie", "PHPSESSID=" + sessionId)
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            int status = response.code();
            if (status == 200) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp post error >> ex = {}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }
}

